package com.ddyx.common;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

/**
 * <p>Title: HttpUtils</p> 
 * <p>Description: 
 *			Http请求-GET/POST请求
 * </p>  
 * @author: JiangShuai 
 * @date:   2018年2月8日 下午7:46:57
 * @Copyright: 2018 xxx Inc. All rights reserved. 
 * <p>注意：本内容仅限于xxx传阅，禁止外泄以及用于其他的商业目 </p>
 */
public class HttpUtils {
 
	/**
	 * <p>Title: doGet</p>
	 * <p>Description: 
	 * 		使用URLConnection实现GET请求 
	 * </p>
	 * @param urlStr
	 * 		请求路径
	 * @return
	 * @throws Exception
	 */
    public static String doGet(String urlStr) throws Exception {
    	//1.实例化一个java.net.URL对象
        URL url = new URL(urlStr);
        //2.通过URL对象的openConnection()方法得到一个java.net.URLConnection
        URLConnection urlConnection = url.openConnection(); //打开连接
        //3.通过URLConnection对象的getInputStream()方法获得输入流
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));//获取输入流  
        String line = null;
        //4.读取输入流
        StringBuilder sb = new StringBuilder();  
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");  
        }
        //5.关闭资源
        br.close();
        return sb.toString();
    }
	 
    /**
     * <p>Title: doPost</p>
     * <p>Description: 
     * 		使用URLConnection实现POST请求(可以带多个附件)
     * </p>
     * @param urlStr
     * 		请求路径
     * @param textMap
     * 		普通参数
     * @param fileMap
     * 		文件参数
     * @return
     */
    public static String doPost(String urlStr,Map<String, String> textMap, Map<String, String> fileMap) { 
        String res = "";  
        HttpURLConnection conn = null;  
        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符    
        int code = 500;
        try {  
            URL url = new URL(urlStr);  
            conn = (HttpURLConnection) url.openConnection();  
            conn.setConnectTimeout(5000);  
            conn.setReadTimeout(30000);  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            conn.setUseCaches(false);  
            conn.setRequestMethod("POST");  
            conn.setRequestProperty("Connection", "Keep-Alive");  
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");  
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());  
            //text
            if (textMap != null) {  
                StringBuffer strBuf = new StringBuffer();  
                Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry<String, String> entry = iter.next();  
                    String inputName = (String) entry.getKey();  
                    String inputValue = (String) entry.getValue();  
                    if (StringUtils.isBlank(inputValue)) {  
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");  
                    strBuf.append(inputValue);
                }  
                out.write(strBuf.toString().getBytes());  
            }
            //file    
            if (fileMap != null) {  
                Iterator<Map.Entry<String, String>> iter = fileMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry<String, String> entry = iter.next();  
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();  
                    if (StringUtils.isBlank(inputValue)) {  
                        continue;  
                    }  
                    File file = new File(inputValue);  
                    String filename = file.getName();
                    
                    //自动获取文件类型(效率慢)  跟下面的二选一
                    /*MagicMatch match = Magic.getMagicMatch(file, false, true);  
                    String contentType = match.getMimeType(); */
                    
                    //传值判断文件类型(效率快)
                    String contentType="";
                    if (filename.endsWith(".png") || filename.endsWith(".PNG")) {
                        contentType = "image/png"; 
                    }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")
                        || filename.endsWith(".JPG") || filename.endsWith(".JPEG") || filename.endsWith(".JPE")) {
                         contentType = "image/jpeg";
                    }else if (filename.endsWith(".gif") || filename.endsWith(".GIF")) {
                         contentType = "image/gif";
                    }else if (filename.endsWith(".ico") || filename.endsWith(".ICO")) {
                        contentType = "image/image/x-icon";
                    }else {
                        contentType = "application/octet-stream";
                    }
                    
                    StringBuffer strBuf = new StringBuffer();  
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");  
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;  
                    byte[] bufferOut = new byte[1024];  
                    while ((bytes = in.read(bufferOut)) != -1) {  
                        out.write(bufferOut, 0, bytes);  
                    }  
                    in.close();  
                }  
            }  
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
            //获取响应状态码  
            code = conn.getResponseCode();
            System.out.println("code="+code);
            out.write(endData);  
            out.flush();  
            out.close();  
            // 读取返回数据    
            StringBuffer strBuf = new StringBuffer();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
                strBuf.append(line).append("\n");  
            }  
            res = strBuf.toString();  
            System.out.println("res="+res);
            reader.close(); 
        } catch (Exception e) {
            System.out.println("发送POST请求出错。" + urlStr);  
            //e.printStackTrace();
            return "{\"msg\" : \"发送请求异常\",\"code\" : "+code+"}";
        } finally {  
            if (conn != null) {  
                conn.disconnect();  
                conn = null;  
            }  
        }
        if(200==code) {
        	return res;
        }
        return "{\"msg\" : \"请求异常\",\"code\" : "+code+"}";
    }
    
}
